import React, {useEffect, useState} from "react";
import {Button, Input, message, Modal, Pagination, Space, Table, TableProps, Tag} from "antd";
import UserVo = API.UserVo;
import {delById, getUserById, getUserByPage, updateUser} from "@/services/swagger/userController";

const UserManager: React.FC = () => {

  const columns: TableProps<UserVo>['columns'] = [
    {
      title: '用户id',
      dataIndex: 'id',
      key: 'id',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '用户账号',
      dataIndex: 'userAccount',
      key: 'userAccount',
    },
    {
      title: '用户昵称',
      dataIndex: 'userName',
      key: 'address',
    },
    {
      title: '用户角色',
      key: 'tags',
      dataIndex: 'userRole',
      render: (_, { userRole }) => {
        let color = 'green';
        if (userRole === 'admin') color = 'geekblue';
        if (userRole === 'user') color = 'green';
        return <Tag color={color}>{userRole?.toLocaleUpperCase()}</Tag>
      }
    },
    {
      title: '创建时间',
      key: 'createTime',
      dataIndex: 'createTime'
    },
    {
      title: '修改时间',
      key: 'updateTime',
      dataIndex: 'updateTime'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={async () => {
            const res = await delById({id: record.id})
            if (res.code === 0){
              message.success("删除成功");
              await getUserList()
            }else {
              message.error("删除失败");
            }
          }}>删除</a>
          <a onClick={async () => {
            // 打开对话框
            showModal(record.id)
          }} >修改</a>
        </Space>
      ),
    },
  ];

  const [userVoList, setUserVoList] = useState<API.UserVo[] | undefined>([])
  const [current, setCurrent] = useState(1)
  const [total, setTotal] = useState<number | undefined>(0)
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [pageSize, setPageSize] = useState(10)
  const [userUpdateRequet, setUserUpdateRequest] = useState<API.UserUpdateRequest>({})
  const [userVo, setUserVo] = useState<API.UserVo | any>({})
  const [userQueryRequest, setUserQueryRequest] = useState<API.UserQueryRequest>({
    current: 1,
    pageSize: 10
  })

  /**
   * 获取用户列表
   */
  const getUserList = async () => {
    const data = await getUserByPage(userQueryRequest);
    if (data.code === 0){
      message.success("获取用户列表成功")
      setUserVoList(data.data);
      setTotal(userVoList?.length)
    }else {
      message.error("获取用户列表失败： " + data.message);
      setUserVoList([])
      setTotal(0)
    }
  }

  const reSetForm = async () => {
    setUserQueryRequest({...userQueryRequest, userAccount: "", id: undefined})
    await getUserList();
  }
  /**
   * 处理分页变化
   */
  const changePage = (currentPage: number, currentPageSize: number) => {
      setCurrent(currentPage);
      setPageSize(currentPageSize);
  }


  const showModal = async (id: any) => {
    setIsModalOpen(true);
    // 查询用户
    const res = await getUserById({userId: id})
    if (res.code === 0){
      console.log("当前用户" + res);
      setUserVo(res.data);
    }
  };

  /**
   * 根据用户id修改用户信息
   */
  const updateUserById = async () => {
    setUserUpdateRequest({...userUpdateRequet, id: userVo.id})
    const res = await updateUser(userUpdateRequet)
    if (res.code === 0){
      message.success("修改成功")
    }
  }

  const handleOk = async () => {
    await updateUserById()
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // 进入页面就获取用户列表
  useEffect(() => {
    getUserList().then(r => {})
  },[current, pageSize])
  return (
    <div>
      <h1>用户管理</h1>
      搜索：<Input  placeholder="输入要查找的账号" value={userQueryRequest.userAccount} onChange={(e) => {
        setUserQueryRequest({...userQueryRequest, userAccount: e.target.value || undefined})}} />
      <Input placeholder="请输入用户id" value={userQueryRequest.id} onChange={(e) => {
        setUserQueryRequest({...userQueryRequest, id: e.target.value || undefined})
      }} />
      <Button onClick={getUserList}>搜索</Button>
      <Button onClick={reSetForm}>重置</Button>
      <Table<UserVo> columns={columns} dataSource={userVoList} rowKey="id" pagination={false}/>
      <Pagination style={{ marginTop: 16, textAlign: 'right' }} current={current} pageSize={pageSize} total={total} onChange={changePage} showSizeChanger />

      <Modal
        title="修改用户"
        closable={{ 'aria-label': 'Custom Close Button' }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
       用户id： {userVo.id}
        <br/>
        用户账号：<Input value={userVo.userAccount} onChange={(e) => {
        setUserUpdateRequest({...userUpdateRequet, userAccount: e.target.value})
      }} />
        用户昵称：<Input value={userVo.userName} onChange={(e) => {
        setUserUpdateRequest({...userUpdateRequet, userName: e.target.value })
      }} />
      </Modal>
    </div>
  );
}
export default UserManager;
